<!doctype html><html lang=zh-hans>
<head>
<meta charset=utf-8>
<meta name=viewport content="width=device-width,initial-scale=1">
<meta http-equiv=x-ua-compatible content="IE=edge">
<meta name=author content="小李刀刀">
<meta name=description content="过滤器对象用于对 PSR-7 或者任何其它的输入数据进行复杂的数据验证和筛选过滤。你可以手动创建过滤器，也可以使用脚手架提供的命令 php app.php create:filter my: namespace App\Filter; use Spiral\Filters\Filter; class MyFilter extends Filter { protected const SCHEMA = [ ]; protected const VALIDATES = [ ]; protected const SETTERS = [ ]; } 有了过滤器类之后，要创建具体的实例，可以借助 Spiral\Filter\FilterProviderInterface 接口的 createFilter 方法，或者采用最简单的手段——方法注入： use App\Filter\MyFilter;">
<meta name=theme-color content="#3f51b5">
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css integrity="sha256-uFVgMKfistnJAfoCUQigIl+JfUaP47GrRKjf6CTPVmw=" crossorigin=anonymous>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-1/css/all.min.css integrity="sha256-4w9DunooKSr3MFXHXWyFER38WmPdm361bQS/2KUWZbU=" crossorigin=anonymous>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin=anonymous>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/tomorrow-night.min.css crossorigin=anonymous title=hl-light>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/tomorrow-night.min.css crossorigin=anonymous title=hl-dark disabled>
<script src=https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.1.2/lazysizes.min.js integrity="sha256-Md1qLToewPeKjfAHU1zyPwOutccPAm5tahnaw7Osw0A=" crossorigin=anonymous async></script>
<link rel=stylesheet href="https://fonts.font.im/css?family=Source+Code+Pro:300,400,500,600,700&subset=latin-ext&display=swap">
<link rel=stylesheet href=/css/academic.css>
<script>(function(b,d,e,a,g){b[a]=b[a]||[],b[a].push({'gtm.start':(new Date).getTime(),event:'gtm.js'});var f=d.getElementsByTagName(e)[0],c=d.createElement(e),h=a!='dataLayer'?'&l='+a:'';c.async=!0,c.src='https://www.googletagmanager.com/gtm.js?id='+g+h,f.parentNode.insertBefore(c,f)})(window,document,'script','dataLayer','GTM-5KZH8N7')</script>
<link rel=manifest href=/index.webmanifest>
<link rel=icon type=image/png href=/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_32x32_fill_lanczos_center_3.png>
<link rel=apple-touch-icon type=image/png href=/images/icon_hu0b7a4cb9992c9ac0e91bd28ffd38dd00_9727_192x192_fill_lanczos_center_3.png>
<link rel=canonical href=https://studyspiral.cn/docs/filters/filter/>
<meta property="twitter:card" content="summary">
<meta property="og:site_name" content="Spiral中文网">
<meta property="og:url" content="https://studyspiral.cn/docs/filters/filter/">
<meta property="og:title" content="过滤器 | Spiral中文网">
<meta property="og:description" content="过滤器对象用于对 PSR-7 或者任何其它的输入数据进行复杂的数据验证和筛选过滤。你可以手动创建过滤器，也可以使用脚手架提供的命令 php app.php create:filter my: namespace App\Filter; use Spiral\Filters\Filter; class MyFilter extends Filter { protected const SCHEMA = [ ]; protected const VALIDATES = [ ]; protected const SETTERS = [ ]; } 有了过滤器类之后，要创建具体的实例，可以借助 Spiral\Filter\FilterProviderInterface 接口的 createFilter 方法，或者采用最简单的手段——方法注入： use App\Filter\MyFilter;"><meta property="og:image" content="https://studyspiral.cn/images/logo.svg">
<meta property="twitter:image" content="https://studyspiral.cn/images/logo.svg"><meta property="og:locale" content="zh-Hans">
<meta property="article:published_time" content="2020-04-12T23:23:35+08:00">
<meta property="article:modified_time" content="2020-08-28T15:38:18+08:00">
<script src=https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.1/cookieconsent.min.js integrity="sha256-5VhCqFam2Cn+yjw61zbBNrbHVJ6SRydPeKopYlngbiQ=" crossorigin=anonymous></script>
<link rel=stylesheet href=https://cdnjs.cloudflare.com/ajax/libs/cookieconsent2/3.1.1/cookieconsent.min.css integrity="sha256-zQ0LblD/Af8vOppw18+2anxsuaz3pWYyVWi+bTvTH8Q=" crossorigin=anonymous>
<script>window.addEventListener("load",function(){window.cookieconsent.initialise({palette:{popup:{background:"#3f51b5",text:"#fff"},button:{background:"#fff",text:"#3f51b5"}},theme:"classic",content:{message:"本网站使用cookies来确保您在本网站上获得最佳体验。",dismiss:"知道了!",link:"了解更多",href:"https://www.cookiesandyou.com"}})})</script>
<title>过滤器 | Spiral中文网</title>
</head>
<body id=top data-spy=scroll data-offset=70 data-target=#TableOfContents>
<aside class=search-results id=search>
<div class=container>
<section class=search-header>
<div class="row no-gutters justify-content-between mb-3">
<div class=col-6>
<h1>搜索</h1>
</div>
<div class="col-6 col-search-close">
<a class=js-search href=#><i class="fas fa-times-circle text-muted" aria-hidden=true></i></a>
</div>
</div>
<div id=search-box>
<input name=q id=search-query placeholder=搜索... autocapitalize=off autocomplete=off autocorrect=off spellcheck=false type=search>
</div>
</section>
<section class=section-search-results>
<div id=search-hits>
</div>
</section>
</div>
</aside>
<nav class="navbar navbar-expand-lg navbar-light compensate-for-scrollbar" id=navbar-main>
<div class=container>
<div class="d-none d-lg-inline-flex">
<a class=navbar-brand href=/><img src=/images/logo.svg alt=Spiral中文网>Spiral中文网</a>
</div>
<button type=button class=navbar-toggler data-toggle=collapse data-target=#navbar-content aria-controls=navbar aria-expanded=false aria-label=切换导航>
<span><i class="fas fa-bars"></i></span>
</button>
<div class="navbar-brand-mobile-wrapper d-inline-flex d-lg-none">
<a class=navbar-brand href=/><img src=/images/logo.svg alt=Spiral中文网>Spiral中文网</a>
</div>
<div class="navbar-collapse main-menu-item collapse justify-content-end" id=navbar-content>
<ul class="navbar-nav d-md-inline-flex">
<li class=nav-item>
<a class=nav-link href=/docs/basics/quick-start/><span>教程</span></a>
</li>
<li class=nav-item>
<a class="nav-link active" href=/docs/><span>文档</span></a>
</li>
<li class=nav-item>
<a class=nav-link href=/post/><span>文章</span></a>
</li>
</ul>
</div>
<ul class="nav-icons navbar-nav flex-row ml-auto d-flex pl-md-2">
<li class=nav-item>
<a class="nav-link js-search" href=#><i class="fas fa-search" aria-hidden=true></i></a>
</li>
</ul>
</div>
</nav>
<div class="container-fluid docs">
<div class="row flex-xl-nowrap">
<div class="col-12 col-md-3 col-xl-2 docs-sidebar">
<form class="docs-search d-flex align-items-center">
<button class="btn docs-toggle d-md-none p-0 mr-3" type=button data-toggle=collapse data-target=#docs-nav aria-controls=docs-nav aria-expanded=false aria-label="Toggle section navigation">
<span><i class="fas fa-bars"></i></span>
</button>
<input name=q type=search class=form-control placeholder=搜索... autocomplete=off>
</form>
<nav class="collapse docs-links" id=docs-nav>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/extension/dotenv/>Dotenv</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/>总览</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse show">
<li>
<a href=/docs/>Spiral介绍</a>
</li>
<li>
<a href=/docs/about/contributing/>贡献指引</a>
</li>
<li>
<a href=/docs/about/semver/>版本说明</a>
</li>
<li>
<a href=/docs/about/license/>授权协议</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/http/psr-15/>定制 PSR-15 处理器</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/start/install/>快速开始</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/start/install/>安装指引</a>
</li>
<li>
<a href=/docs/start/workers/>应用工作进程</a>
</li>
<li>
<a href=/docs/start/structure/>应用程序结构</a>
</li>
<li>
<a href=/docs/start/configuration/>默认配置</a>
</li>
<li>
<a href=/docs/start/commands/>控制台命令</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/basics/quick-start/>入门基础</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/basics/quick-start/>上手指南</a>
</li>
<li>
<a href=/docs/basics/scaffolding/>脚手架</a>
</li>
<li>
<a href=/docs/basics/prototype/>原型开发辅助</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/framework/design/>核心框架</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/framework/design/>设计理念</a>
</li>
<li>
<a href=/docs/framework/application-server/>应用服务器</a>
</li>
<li>
<a href=/docs/framework/config/>配置对象</a>
</li>
<li>
<a href=/docs/framework/kernel/>内核与环境</a>
</li>
<li>
<a href=/docs/framework/container/>容器</a>
</li>
<li>
<a href=/docs/framework/bootloaders/>引导程序</a>
</li>
<li>
<a href=/docs/framework/scopes/>IoC 作用域</a>
</li>
<li>
<a href=/docs/framework/memory/>静态高速缓存</a>
</li>
<li>
<a href=/docs/framework/finalizers/>终结器</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/cookbook/annotated-routes/>速查手册</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/cookbook/annotated-routes/>注解式路由</a>
</li>
<li>
<a href=/docs/cookbook/injector/>容器注入器</a>
</li>
<li>
<a href=/docs/cookbook/domain-core/>领域内核、控制器</a>
</li>
<li>
<a href=/docs/cookbook/golang-library/>Golang服务集成</a>
</li>
<li>
<a href=/docs/cookbook/custom-dispatcher/>自定义调度器</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/component/files/>常用组件</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/component/files/>文件和目录</a>
</li>
<li>
<a href=/docs/component/reactor/>代码生成</a>
</li>
<li>
<a href=/docs/component/tokenizer/>静态分析工具</a>
</li>
<li>
<a href=/docs/component/metrics/>应用指标</a>
</li>
<li>
<a href=/docs/component/data-grid/>数据网格</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/console/configuration/>控制台</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/console/configuration/>安装和配置</a>
</li>
<li>
<a href=/docs/console/commands/>用户命令</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/http/configuration/>HTTP</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/http/configuration/>安装配置</a>
</li>
<li>
<a href=/docs/http/lifecycle/>请求生命周期</a>
</li>
<li>
<a href=/docs/http/request-response/>请求和响应</a>
</li>
<li>
<a href=/docs/http/routing/>路由</a>
</li>
<li>
<a href=/docs/http/errors/>错误页面</a>
</li>
<li>
<a href=/docs/http/middleware/>中间件</a>
</li>
<li>
<a href=/docs/http/golang/>Golang 中间件</a>
</li>
<li>
<a href=/docs/http/cookies/>Cookies</a>
</li>
<li>
<a href=/docs/http/session/>Session</a>
</li>
<li>
<a href=/docs/http/csrf/>CSRF 防护</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/security/encrypter/>安全</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/security/encrypter/>数据加密</a>
</li>
<li>
<a href=/docs/security/validation/>数据验证</a>
</li>
<li>
<a href=/docs/security/rbac/>基于角色的权限控制</a>
</li>
<li>
<a href=/docs/security/authentication/>用户认证</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/filters/configuration/>请求过滤</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse show">
<li>
<a href=/docs/filters/configuration/>安装和配置</a>
</li>
<li class=active>
<a href=/docs/filters/filter/>过滤器</a>
</li>
<li>
<a href=/docs/filters/composite/>复合过滤器</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/database/configuration/>数据库</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/database/configuration/>安装与配置</a>
</li>
<li>
<a href=/docs/database/access/>访问数据</a>
</li>
<li>
<a href=/docs/database/isolation/>逻辑隔离</a>
</li>
<li>
<a href=/docs/database/query-builders/>查询构造器</a>
</li>
<li>
<a href=/docs/database/transactions/>Transactions</a>
</li>
<li>
<a href=/docs/database/introspection/>Schema Introspection</a>
</li>
<li>
<a href=/docs/database/declaration/>Declaration</a>
</li>
<li>
<a href=/docs/database/migrations/>Migrations</a>
</li>
<li>
<a href=/docs/database/errata/>Errata</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/cycle/configuration/>Cycle ORM</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/cycle/configuration/>Configuration</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/queue/configuration/>队列任务</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/queue/configuration/>Configuration</a>
</li>
<li>
<a href=/docs/queue/scraper/>网站爬虫</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/views/configuration/>视图</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/views/configuration/>Configuration</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link href=/docs/stempler/configuration/>Stempler 模板</a>
<ul class="nav docs-sidenav docs-sidenav-sub collapse">
<li>
<a href=/docs/stempler/configuration/>Configuration</a>
</li>
<li>
<a href=/docs/stempler/directives/>Directives</a>
</li>
</ul>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>国际化</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>GRPC</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>事件广播</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>调试及性能</a>
</div>
<div class=docs-toc-item>
<a class=docs-toc-link>扩展</a>
</div>
</nav>
</div>
<div class="d-none d-xl-block col-xl-2 docs-toc">
<ul class="nav toc-top">
<li><a href=# id=back_to_top class=docs-toc-title>在本页</a></li>
</ul>
<nav id=TableOfContents>
<ul>
<li><a href=#过滤器结构>过滤器结构</a>
<ul>
<li><a href=#点表示法>点表示法</a></li>
<li><a href=#其它数据源>其它数据源</a></li>
<li><a href=#路由参数>路由参数</a></li>
<li><a href=#设置器setters>设置器（Setters）</a></li>
</ul>
</li>
<li><a href=#验证>验证</a>
<ul>
<li><a href=#自定义错误>自定义错误</a></li>
</ul>
</li>
<li><a href=#使用>使用</a>
<ul>
<li><a href=#获取字段>获取字段</a></li>
<li><a href=#获取错误>获取错误</a></li>
</ul>
</li>
<li><a href=#继承>继承</a></li>
</ul>
</nav>
</div>
<main class="col-12 col-md-9 col-xl-8 py-md-3 pl-md-5 docs-content" role=main>
<article class=article>
<div class="alert alert-warning" role=alert>
官方文档中文版翻译工作仍在进行中，欢迎 <a href=/post/join-translation/>参与翻译</a>。
</div>
<div class=docs-article-container>
<h1>过滤器</h1>
<div class=article-style>
<p>过滤器对象用于对 PSR-7 或者任何其它的输入数据进行复杂的数据验证和筛选过滤。你可以手动创建过滤器，也可以使用脚手架提供的命令 <code>php app.php create:filter my</code>:</p>
<pre><code class=language-php>namespace App\Filter;

use Spiral\Filters\Filter;

class MyFilter extends Filter
{
    protected const SCHEMA    = [
    ];

    protected const VALIDATES = [
    ];

    protected const SETTERS   = [
    ];
}
</code></pre>
<p>有了过滤器类之后，要创建具体的实例，可以借助 <code>Spiral\Filter\FilterProviderInterface</code> 接口的 <code>createFilter</code> 方法，或者采用最简单的手段——方法注入：</p>
<pre><code class=language-php>use App\Filter\MyFilter;

class HomeController
{
    public function index(MyFilter $filter)
    {
        dump($filter);
    }
}
</code></pre>
<h2 id=过滤器结构>过滤器结构</h2>
<p>任何一个过滤器对象的核心构成是 <code>SCHEMA</code>；这个常量定义了由输入对象提供的字段名和字段值之间的映射关系。
每个键值对都需要定义为 <code>field</code> => <code>source:origin</code> 或者 <code>filter</code> => <code>source</code> 的形式。<strong>source</strong> 用户输入数据的子集。在 HTTP 范围内，<strong>source</strong> 可以是 <code>cookie</code>、<code>data</code>、<code>query</code>、<code>input</code>（等于 <code>data</code> 加 <code>query</code>）、<code>header</code>、<code>file</code>、<code>server</code>. <strong>origin</strong> 是字段名称（支持点表示法）。</p>
<blockquote>
<p>你可以使用 (/docs/http/request-response/) 中的任何一个 input bag 作为数据源。</p>
</blockquote>
<p>比如我们可以告诉过滤器把 <code>login</code> 字段指向查询参数 <code>username</code>：</p>
<pre><code class=language-php>namespace App\Filter;

use Spiral\Filters\Filter;

class MyFilter extends Filter
{
    protected const SCHEMA = [
        'login' =&gt; 'query:username'
    ];
}
</code></pre>
<p>在过滤器中可以混合使用多个数据源：</p>
<pre><code class=language-php>namespace App\Filter;

use Spiral\Filters\Filter;

class MyFilter extends Filter
{
    protected const SCHEMA = [
        'redirectTo'   =&gt; 'query:redirectURL',
        'memberCookie' =&gt; 'cookie:memberCookie',
        'username'     =&gt; 'data:username',
        'password'     =&gt; 'data:password',
        'rememberMe'   =&gt; 'data:rememberMe'
    ];
}
</code></pre>
<blockquote>
<p>最常用的数据源是 <code>data</code>（指向 PSR-7 解析的主体），使用这个数据源可以从传入的 JSON 数据中取值。</p>
</blockquote>
<h3 id=点表示法>点表示法</h3>
<p>数据的 <strong>origin</strong> 可以用点表示法来指向嵌套结构内部的字段。例如：</p>
<pre><code class=language-php>namespace App\Filter;

use Spiral\Filters\Filter;

class MyFilter extends Filter
{
    protected const SCHEMA = [
        'firstName' =&gt; 'data:name.first'
    ];

    protected const VALIDATES = [
        'firstName' =&gt; [
            ['notEmpty']
        ]
    ];

    protected const SETTERS = [
        'firstName' =&gt; 'strval'
    ];
}
</code></pre>
<p>上面的例子可以接受和验证下面的数据结构：</p>
<pre><code class=language-json>{
  &quot;names&quot;: {
    &quot;first&quot;: &quot;Antony&quot;
  }
}
</code></pre>
<blockquote>
<p>错误信息会正确地挂载到对应的字段位置。当然你可以混合使用不同的过滤器来实现更复杂的用例。</p>
</blockquote>
<h3 id=其它数据源>其它数据源</h3>
<p>按照设计，你可以使用 <code>(/docs/http/request-response/)</code> 的任何方法作为数据源，其中 <strong>origin</strong> 是传递参数。以下的数据源都是可用的：</p>
<table>
<thead>
<tr>
<th>数据源</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>uri</td>
<td>以 <code>Psr\Http\Message\UriInterface</code> 表示的当前请求的 URI</td>
</tr>
<tr>
<td>path</td>
<td>当前请求的路径部分</td>
</tr>
<tr>
<td>method</td>
<td>HTTP 方法 (GET, POST, &mldr;)</td>
</tr>
<tr>
<td>isSecure</td>
<td>如果使用了 https</td>
</tr>
<tr>
<td>isAjax</td>
<td>如果 <code>X-Requested-With</code> 设为 <code>xmlhttprequest</code></td>
</tr>
<tr>
<td>isJsonExpected</td>
<td>如果客户端的 <code>Accept</code> 设为 <code>application/json</code></td>
</tr>
<tr>
<td>remoteAddress</td>
<td>用户的 IP 地址</td>
</tr>
</tbody>
</table>
<blockquote>
<p>请阅读 (/docs/http/request-response/) 了解更多。</p>
</blockquote>
<p>举个例子，如果需要检查用户请求是否通过 https 协议发起：</p>
<pre><code class=language-php>namespace App\Filter;

use Spiral\Filters\Filter;

class MyFilter extends Filter
{
    protected const SCHEMA = [
        'httpsRequest' =&gt; 'isSecure'
    ];

    protected const VALIDATES = [
        'httpsRequest' =&gt; [
            ['notEmpty', 'error' =&gt; '不是安全连接']
        ]
    ];
}
</code></pre>
<blockquote>
<p>有关于验证规则，下面的文档会进一步介绍。</p>
</blockquote>
<h3 id=路由参数>路由参数</h3>
<p>每个路由都会把匹配的参数写入到 <code>ServerRequestInterface</code> 的 <code>matches</code> 属性，因此在过滤器对象中也可以使用 <code>attribute:matches.{name}</code> 的表示法来访问路由参数：</p>
<pre><code class=language-php>$router-&gt;setRoute(
    'sample',
    new Route('/action/&lt;id&gt;.html', new Controller(HomeController::class))
);
</code></pre>
<p>对于上面的路由，可以这样定义过滤器：</p>
<pre><code class=language-php>namespace App\Filter;

use Spiral\Filters\Filter;

class MyFilter extends Filter
{
    protected const SCHEMA = [
        'routeID' =&gt; 'attribute:matches.id'
    ];
}
</code></pre>
<h3 id=设置器setters>设置器（Setters）</h3>
<p>在把输入的值传递给验证器之前，可以使用设置器对输入的值进行类型转换。如果在转换时抛出了类型转换错误，那么筛选器会把该字段的值设定为 <code>null</code>：</p>
<pre><code class=language-php>namespace App\Filter;

use Spiral\Filters\Filter;

class MyFilter extends Filter
{
    protected const SCHEMA = [
        'number' =&gt; 'query:number'
    ];

    protected const VALIDATES = [
        'number' =&gt; [
            ['notEmpty'],
            ['number::higher', 5]
        ]
    ];

    protected const SETTERS = [
        'number' =&gt; 'intval'
    ];
}
</code></pre>
<blockquote>
<p>可以使用任何 PHP 内置函数例如 <code>intval</code>、<code>strval</code> 等。</p>
</blockquote>
<pre><code class=language-php>namespace App\Controller;

use App\Filter\MyFilter;

class HomeController
{
    public function index(MyFilter $filter)
    {
        dump($filter-&gt;number); // 总是数字
    }
}
</code></pre>
<blockquote>
<p>译注：验证用户输入时，请谨慎使用设置器，这会使输入验证规则失效，且筛选后的数据与用户输入不一致</p>
</blockquote>
<h2 id=验证>验证</h2>
<p>验证规则的定义与 (/docs/security/validation/) 组件中的方法和规则一致。</p>
<pre><code class=language-php>namespace App\Filter;

use Spiral\Filters\Filter;

class MyFilter extends Filter
{
    protected const SCHEMA = [
        'name' =&gt; 'data:name'
    ];

    protected const VALIDATES = [
        'name' =&gt; [
            ['notEmpty']
        ]
    ];
}
</code></pre>
<p>可以使用所有的检查器、条件和规则。</p>
<h3 id=自定义错误>自定义错误</h3>
<p>与安全组件中的数据验证一样，你可以给任何一条验证规则定义自己的错误信息。</p>
<pre><code class=language-php>namespace App\Filter;

use Spiral\Filters\Filter;

class MyFilter extends Filter
{
    protected const SCHEMA = [
        'name' =&gt; 'data:name'
    ];

    protected const VALIDATES = [
        'name' =&gt; [
            ['notEmpty', 'error' =&gt; 'Name 不能为空']
        ]
    ];
}
</code></pre>
<p>如果想要在定义之后对错误消息进行本地化，可以把错误信息文字用 <code>[[]]</code> 包围起来，可以自动生成本地化翻译的索引并在显示时自动替换为对应的语言（在语言包中定义）：</p>
<pre><code class=language-php>namespace App\Filter;

use Spiral\Filters\Filter;

class MyFilter extends Filter
{
    protected const SCHEMA = [
        'name' =&gt; 'data:name'
    ];

    protected const VALIDATES = [
        'name' =&gt; [
            ['notEmpty', 'error' =&gt; '[[Name must not be empty]]']
        ]
    ];
}
</code></pre>
<h2 id=使用>使用</h2>
<p>一旦配置好过滤器，就可以直接访问它的字段（过滤之后的数据），检查数据合法性并在发生错误时返回一组错误信息。</p>
<blockquote>
<p>建议在数据到达控制器之前使用(/docs/cookbook/domain-core/)对过滤器的数据进行必要的验证。</p>
</blockquote>
<h3 id=获取字段>获取字段</h3>
<p>要访问经过过滤的数据字段，使用 <code>getField</code> 和 <code>getFileds</code> 方法。举个例子，假设有如下的过滤器：</p>
<pre><code class=language-php>namespace App\Filter;

use Spiral\Filters\Filter;

class MyFilter extends Filter
{
    protected const SCHEMA = [
        'name'  =&gt; 'data:name',
        'email' =&gt; 'data:email'
    ];

    protected const VALIDATES = [
        'name' =&gt; [
            ['notEmpty']
        ]
    ];

    protected const SETTERS = [

    ];
}
</code></pre>
<p>在数据存在且通过验证的情况下，以下字段可以访问：</p>
<pre><code class=language-php>public function index(MyFilter $filter)
{
    dump($filter-&gt;getFields()); // {name: ..., email: ...}

    dump($filter-&gt;getField('name'));

    // 同上
    dump($filter-&gt;email);
}
</code></pre>
<h3 id=获取错误>获取错误</h3>
<p>要检查过滤器的数据是否有效，可以使用 <code>isValid</code> 方法，无效字段的错误可以通过 <code>getErrors</code> 获取：</p>
<pre><code class=language-php>public function index(MyFilter $filter)
{
    if (!$filter-&gt;isValid()) {
        dump($filter-&gt;getErrors());
    }
}
</code></pre>
<p>错误会自动映射到正确的原始属性名称，例如：</p>
<pre><code class=language-php>namespace App\Filter;

use Spiral\Filters\Filter;

class MyFilter extends Filter
{
    protected const SCHEMA = [
        'name' =&gt; 'data:names.name.0'
    ];

    protected const VALIDATES = [
        'name' =&gt; [
            ['notEmpty']
        ]
    ];

    protected const SETTERS = [

    ];
}
</code></pre>
<p>在 <code>name</code> 字段无效时，上面的过滤器会响应下面的错误：</p>
<pre><code class=language-json>{
  &quot;status&quot;: 400,
  &quot;errors&quot;: {
    &quot;names&quot;: {
      &quot;name&quot;: &quot;This value is required.&quot;
    }
  }
}
</code></pre>
<blockquote>
<p>错误的格式和(/docs/security/validation/)中描述的一致。</p>
</blockquote>
<h2 id=继承>继承</h2>
<p>你可以从一个过滤器扩展出另一个过滤器，<code>SCHEMA</code>、<code>VALIDATES</code> 和 <code>SETTERS</code> 常量会被继承：</p>
<pre><code class=language-php>namespace App\Filter;

class MyFilter extends BaseFilter
{
    protected const SCHEMA = [
        'name' =&gt; 'data:name'
    ];

    protected const VALIDATES = [
        'name' =&gt; [
            ['notEmpty']
        ]
    ];
}
</code></pre>
<p>上面例子中的 <code>BaseFilter</code> 代码如下：</p>
<pre><code class=language-php>namespace App\Filter;

use Spiral\Filters\Filter;

class BaseFilter extends Filter
{
    protected const SCHEMA = [
        'token' =&gt; 'data:token'
    ];

    protected const VALIDATES = [
        'token' =&gt; [
            ['notEmpty']
        ]
    ];
}
</code></pre>
<p>在上例中，<code>MyFilter</code> 同样要求 <code>token</code> 字段必须填写：</p>
<pre><code class=language-json>{
  &quot;status&quot;: 400,
  &quot;errors&quot;: {
    &quot;token&quot;: &quot;This value is required.&quot;,
    &quot;name&quot;: &quot;This value is required.&quot;
  }
}
</code></pre>
</div>
<div class=article-widget>
<div class=post-nav>
<div class=post-nav-item>
<div class=meta-nav>上一页</div>
<a href=/docs/views/configuration/ rel=next>Configuration</a>
</div>
<div class=post-nav-item>
<div class=meta-nav>下一页</div>
<a href=/docs/filters/configuration/ rel=prev>安装和配置</a>
</div>
</div>
</div>
</div>
<div class=body-footer>
<p>最近更新于 2020-08-28</p>
<p class=edit-page>
<a href=https://github.com/krwu/spiraldocs/edit/feat/chinese/zh_CN/filters/filter.md>
<i class="fas fa-pen pr-2"></i>编辑本页
</a>
</p>
</div>
</article>
<footer class=site-footer>
<p class=powered-by><span class=copyright>© 2019 - 2021 <a href=https://studyspiral.cn/>StudySpiral</a> All rights reserved.</span>
</p>
<p class=powered-by>
<a href=http://www.beian.miit.gov.cn/ target=_blank rel="noopener noreferer">粤ICP备14011364号</a>
<a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=44030402001866" target=_blank rel="noopener noreferer"><img style=display:inline-block src=/img/gaba.png>粤公网安备 44030402001866号</a>
</p>
<p id=webify class=powered-by style=display:flex><span style="margin:0 .2rem 0 0;display:block;height:20px;line-height:20px">Powered by</span> <a href=https://webify.cloudbase.net/ target=_blank rel=noopener>CloudBase Webify</a></p>
<script async defer>window.addEventListener('DOMContentLoaded',()=>{const{host:a}=window.location;(a.toLocaleLowerCase()==='docs.studyspiral.cn'||a.indexOf(".app.tcloudbase.com"))&&(document.getElementById('webify').style.display='flex')})</script>
</footer>
</main>
</div>
</div>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.4/imagesloaded.pkgd.min.js integrity="sha256-lqvxZrPLtfffUl2G/e7szqSvPBILGbwmsGE1MKlOi0Q=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.6/isotope.pkgd.min.js integrity="sha256-CBrpuqrMhXwcLLUd5tvQ4euBHCdh7wGlDfNz8vbu/iI=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/highlight.min.js integrity="sha256-eOgo0OtLL4cdq7RdwRUiGKLX9XsIJ7nGhWEKbohmVAQ=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/languages/go.min.js></script>
<script>const code_highlighting=!0</script>
<script>const isSiteThemeDark=!1</script>
<script>const search_config={indexURI:"/index.json",minLength:1,threshold:.3},i18n={no_results:"没有找到结果",placeholder:"搜索...",results:"搜索结果"},content_type={post:"文章",project:"项目",publication:"出版物",talk:"演讲"}</script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/anchor-js/4.1.1/anchor.min.js integrity="sha256-pB/deHc9CGfFpJRjC43imB29Rse8tak+5eXqntO94ck=" crossorigin=anonymous></script>
<script>anchors.add()</script>
<script id=search-hit-fuse-template type=text/x-template>
      <div class="search-hit" id="summary-{{key}}">
      <div class="search-hit-content">
        <div class="search-hit-name">
          <a href="{{relpermalink}}">{{title}}</a>
          <div class="article-metadata search-hit-type">{{type}}</div>
          <p class="search-hit-description">{{snippet}}</p>
        </div>
      </div>
      </div>
    </script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/fuse.js/3.2.1/fuse.min.js integrity="sha256-VzgmKYmhsGNNN4Ph1kMW+BjoYJM2jV5i4IlFoeZA9XI=" crossorigin=anonymous></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.min.js integrity="sha256-4HLtjeVgH0eIB3aZ9mLYF6E8oU5chNdjU6p6rrXpl9U=" crossorigin=anonymous></script>
<script src=/js/academic.min.6f1005d1a84220e2f466ff3d8e712f31.js></script>
<div id=modal class="modal fade" role=dialog>
<div class=modal-dialog>
<div class=modal-content>
<div class=modal-header>
<h5 class=modal-title>引用</h5>
<button type=button class=close data-dismiss=modal aria-label=Close>
<span aria-hidden=true>&#215;</span>
</button>
</div>
<div class=modal-body>
<pre><code class="tex hljs"></code></pre>
</div>
<div class=modal-footer>
<a class="btn btn-outline-primary my-1 js-copy-cite" href=# target=_blank>
<i class="fas fa-copy"></i> 复制
</a>
<a class="btn btn-outline-primary my-1 js-download-cite" href=# target=_blank>
<i class="fas fa-download"></i> 下载
</a>
<div id=modal-error></div>
</div>
</div>
</div>
</div>
</body>
</html>